//
//  PKRadioMainViewController.m
//  PianKe
//
//  Created by ybq on 15/12/21.
//  Copyright © 2015年 B7_Young. All rights reserved.
//

#import "PKRadioMainViewController.h"
#import "PKRadioHeaderView.h"
#import "PKRadioMainListTableViewCell.h"
#import "PKRadioMainModel.h"
#import "PKRadioDetailViewController.h"

@interface PKRadioMainViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *listDatasource;
@property (nonatomic, strong) NSMutableArray *buttonDatasource;
@property (nonatomic, strong) NSMutableArray *carouselDatasource;
@property (nonatomic, strong) PKRadioHeaderView *headerView;
@property (nonatomic, assign) NSInteger requestStart;

@end

@implementation PKRadioMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _listDatasource = [NSMutableArray array];
    _buttonDatasource = [NSMutableArray array];
    _carouselDatasource = [NSMutableArray array];
    // Do any additional setup after loading the view.
    // 请求数据
    [self requestAllData];
    [self creatUI];
    _requestStart = 0;
    
}



- (void)creatUI {
    
    [self changeNavViewTitle];
    
    UIButton *speakButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    speakButton.frame = CGRectMake(kWidth - 97, 10, 18, 18);
    [speakButton setImage:[UIImage imageNamed:@"huatong"] forState:(UIControlStateNormal)];
    [self.navView addSubview:speakButton];
    
    UIButton *textButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    textButton.frame = CGRectMake(kWidth - 85, 10, 70, 20);
    textButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [textButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [textButton setTitle:@"我要当主播" forState:(UIControlStateNormal)];
    [self.navView addSubview:textButton];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kWidth, kHeight - 64)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // MJRefresh
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart = 0;
        [self requestAllData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        _requestStart += 9;
        [self requestListData];
    }];
    
    _headerView = [[PKRadioHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 315)];
    // 添加轮播图和三个button的图片
    [self addImages];
    self.tableView.tableHeaderView = _headerView;
    self.tableView.rowHeight = 90;
    [self.tableView registerClass:[PKRadioMainListTableViewCell class] forCellReuseIdentifier:@"PKRadioMainListTableViewCell"];
    [self.view addSubview:self.tableView];
    
}

- (void)addImages {
    __weak PKRadioMainViewController *myself= self;
    myself.hotlist = ^() {
        // 精选3button
        for (int i = 0; i < 3; i++) {
            PKHotlistButton *hotlistButton = [_headerView viewWithTag:i + 100];
            PKRadioMainModel *hotlistButtonModel = _buttonDatasource[i];
            if (!hotlistButtonModel.isnew) {
                [hotlistButton.bestImageView removeFromSuperview];
            }
            [hotlistButton sd_setImageWithURL:[NSURL URLWithString:hotlistButtonModel.coverimg] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"placehoder"]];
            [hotlistButton addTarget:self action:@selector(infoAction:) forControlEvents:(UIControlEventTouchUpInside)];
        }
        // 轮播图图片
        for (int i = 0; i < 4; i++) {
            UIImageView *carouseImageView = [_headerView viewWithTag:i + 1000];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(carouseAction:)];
            [carouseImageView addGestureRecognizer:tap];
            if (i < 3) {
                PKRadioMainModel *carouseModel = _carouselDatasource[i];
                [carouseImageView sd_setImageWithURL:[NSURL URLWithString:carouseModel.img]];
            } else {
                [carouseImageView sd_setImageWithURL:[NSURL URLWithString:((PKRadioMainModel *)_carouselDatasource[0]).img]];
            }
        }
        
    };

}

// 跳转detail页面
- (void)infoAction:(UIButton *)sender {
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    PKRadioMainModel *model = _buttonDatasource[sender.tag - 100];
    detailVC.radioid = model.radioid;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)carouseAction:(UITapGestureRecognizer *)tap {
    UIImageView *carouselImageView = (UIImageView *)tap.view;
    NSInteger index = carouselImageView.tag - 1000;
    if (carouselImageView.tag == 1003) {
        index = 0;
    }
    PKRadioMainModel *model = _carouselDatasource[index];
    NSString *radioid = [model.url substringFromIndex:12];
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    detailVC.radioid = radioid;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
}

// 自定义请求数据的方法
- (void)requestAllData {
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"07EBFC18-9BF8-47D1-9FEA-79BBF44D4C9E";
    parDic[@"version"] = @"3.0.6";
    
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/ting/radio" parDic:parDic Method:POST finish:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *listArray = dataDic[@"data"][@"alllist"];
        NSArray *buttonArray = dataDic[@"data"][@"hotlist"];
        NSArray *carouselArray = dataDic[@"data"][@"carousel"];
        if (_requestStart == 0) {
            [_listDatasource removeAllObjects];
            [_buttonDatasource removeAllObjects];
            [_carouselDatasource removeAllObjects];
        }
        for (NSDictionary *dic in listArray) {
            PKRadioMainModel *model = [[PKRadioMainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_listDatasource addObject:model];
        }
        
        for (NSDictionary *dic in buttonArray) {
            PKRadioMainModel *model = [[PKRadioMainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_buttonDatasource addObject:model];
        }
        
        for (NSDictionary *dic in carouselArray) {
            PKRadioMainModel *model = [[PKRadioMainModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_carouselDatasource addObject:model];
        }
        [self.tableView.mj_header endRefreshing];
        self.hotlist();
        [self.tableView reloadData];
    } error:^(NSError *error) {
        
    }];
}

// 下拉刷新数据

- (void)requestListData {
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"07EBFC18-9BF8-47D1-9FEA-79BBF44D4C9E";
    parDic[@"version"] = @"3.0.6";
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    parDic[@"limit"] = @"9";
    
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/ting/radio_list" parDic:parDic Method:POST finish:^(NSData *data) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *listArray = dataDic[@"data"][@"list"];
        for (NSDictionary *dic in listArray) {
            
        PKRadioMainModel *model = [[PKRadioMainModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [_listDatasource addObject:model];
            
        }
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        
    }];
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _listDatasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PKRadioMainListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PKRadioMainListTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    PKRadioMainModel *model = _listDatasource[indexPath.row];
    if (!model.isnew) {
        [cell.NewImageView removeFromSuperview];
    }
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    PKRadioMainModel *model = _listDatasource[indexPath.row];
    detailVC.radioid = model.radioid;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
